﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using BusinessLogic;
using BusinessObject;
using Utility;
using System.Web.Security;
using System.Resources;
namespace WebTeamplate
{


    public partial class Admin_ChiTietMatHang : BasePage
    {
        #region Fields
        public string urlList = "DMMatHang.aspx";
        public string validateGroup = "matHang";
        #endregion

        #region ViewStates
        public string Command
        {

            get
            {
                object o = ViewState["Command"];
                if (o != null) return (string)o;
                return string.Empty;
            }

            set { ViewState["Command"] = value; }

        }

        public string MaMatHang
        {

            get
            {

                object o = ViewState["MaMatHang"];
                if (o != null) return (string)o;
                return string.Empty;                //a default
            }
            set { ViewState["MaMatHang"] = value; }

        }

        #endregion

        #region Init,Loads
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientDefaultButton.SetPageDefaultButton(this.Page, btnSave.ClientID);
            if (!Page.IsPostBack)
            {
                CommonFunction.LoadSubCate(drlChungXe, CommonFunction.DEFAULT_CHUNGLOAIXE_CODE, true);
                CommonFunction.InitStatusPublishForComboboxDetail(drlPublish, "1");
                CommonFunction.LoadSubCate(drlFormMHLoaiMH, CommonFunction.DEFAULT_LOAIHANGHOA_CODE, true);
                CommonFunction.LoadSubCate(drlFormMHNhomHH, CommonFunction.DEFAULT_NHOMHANGHOA_CODE, true);
                CommonFunction.LoadSubCate(drlFormMHNuocSX, CommonFunction.DEFAULT_COUNTRY_CODE, true);
                CommonFunction.LoadSubCate(drlDVT, CommonFunction.DEFAULT_UNIT_CODE, true);
                // LoadCurency();
                LoadDMXe();
                InitParamater();
                InitTextControl();
                LoadData();
                drlFormMHLoaiMH.Focus();
            }
        }

        private void LoadDMXe()
        {
            List<DMXeResult> lstResult = DMXeUtil.GetByChungXe(ConvertValueObject.ParseInt(drlChungXe.SelectedValue));
            drlXe.Items.Clear();
            ListItem nullItem = new ListItem(BaseFunctions.COMBOBOX_NULL_VALUE, string.Empty);
            drlXe.Items.Add(nullItem);
            foreach (DMXeResult objXe in lstResult)
            {
                drlXe.Items.Add(new ListItem(objXe.TenXe, objXe.MaXe.ToString()));
            }
        }
        public string GenareteProductCode()
        {
            string result = MatHangUtil.GenerateKey().ToString();
            while (result.ToString().Length < CommonFunction.MAHH_LENGTH)
            {
                result = "0" + result.ToString();
            }
            return result.ToString();
        }
        //private void LoadCurency()
        //{
        //    List<CurencyResult> lstResult = CurencyUtil.GetAll();
        //    foreach (CurencyResult objData in lstResult)
        //    {
        //        if (objData.Code == CommonFunction.DEFAULT_VND_CURENCY)
        //            drlCurency.Items.Add(new ListItem(objData.Name, objData.Code.ToString()));
        //    }
        //}
        private void LoadData()
        {
            if (this.Command == CommonFunction.DEFAULT_COMMAND_ADD)
            {
                txtFormMHMaMatHang.Text = GenareteProductCode();
            }
            else
            {
                MatHang objData = MatHangUtil.Get(this.MaMatHang);
                if (objData != null)
                {
                    if (objData.IsPublished)
                        drlPublish.SelectedValue = "1";
                    else drlPublish.SelectedValue = "0";
                    txtFormMHHieu.Text = objData.Hieu;
                    txtFormMHTenMH.Text = objData.TenMatHang;
                    drlFormMHLoaiMH.SelectedValue = objData.MaLoaiHangHoa.ToString();
                    drlFormMHNuocSX.SelectedValue = objData.MaNuocSanXuat.ToString();
                    drlFormMHNhomHH.SelectedValue = objData.MaNhom.ToString();
                    // txtGiaBan.Text = ConvertValueObject.ParseString(objData.GiaBan);
                    drlDVT.SelectedValue = objData.DVT.ToString();
                    txtMaPhuTung.Text = objData.MaPhuTung;
                    DMXe objXe = DMXeUtil.Get(objData.MaXe);
                    if (objXe != null)
                    {
                        drlChungXe.SelectedValue = objXe.ChungXe.ToString();
                    }
                    LoadDMXe();
                    drlXe.SelectedValue = objData.MaXe.ToString();
                    List<HinhAnhMatHangResult> lstHinhAnh = HinhAnhMatHangUtil.GetAllByMatHang(objData.MaMatHang);
                    BindPicture(lstHinhAnh);
                }
            }
        }

        private void BindPicture(List<HinhAnhMatHangResult> lstHinhAnh)
        {
            if (lstHinhAnh != null && lstHinhAnh.Count > 0)
            {
                string img1 = string.Empty;
                string img2 = string.Empty;
                img1 = lstHinhAnh[0].ImageUrl.ToString();
                try
                {
                    img2 = lstHinhAnh[1].ImageUrl.ToString();
                }
                catch
                {
                }
                ViewPicture(img1, imgHinh1, lbtnDeleteHinh1);
                ViewPicture(img2, imgHinh2, lbtnDeleteHinh2);
            }
        }
        private void ViewPicture(string imageName, System.Web.UI.WebControls.Image imgCtr, LinkButton lbtnDelete)
        {
            string pathlarge = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_LARGE);
            pathlarge += "\\" + imageName;
            if (File.Exists(pathlarge))
            {
                imgCtr.ImageUrl = CommonFunction.DEFAULT_UPLOAD_PRODUCT_LARGE + "\\" + imageName;
                lbtnDelete.Visible = true;
                imgCtr.Visible = true;
            }
            else
            {
                imgCtr.Visible = false;
                lbtnDelete.Visible = false;
            }
        }
        #endregion

        #region Methos

        private void InitParamater()
        {
            this.MaMatHang = CommonFunction.GetValueFromQueryString(this.Page, "id");
            txtFormMHMaMatHang.Text = this.MaMatHang;
            this.Command = CommonFunction.GetValueFromQueryString(this.Page, "act");
            if (this.Command == string.Empty)
                this.Command = CommonFunction.DEFAULT_COMMAND_ADD;
        }

        private void InitTextControl()
        {
            btnSave.Text = Resources.Resource.LABEL_BUTTON_SAVE;
            btnCacel.Text = Resources.Resource.LABEL_BUTTON_CANCEL;
            btnReset.Text = Resources.Resource.LABEL_BUTTON_RESET;
            refvFormMHLoaiMH.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblFormMHLoaiMatHang));
            refvFormMHLoaiMH.ValidationGroup = validateGroup;
            refvPublish.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblPublish));
            refvPublish.ValidationGroup = validateGroup;
            refvFormMHMaMatHang.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblFormMHMaMatHang));
            refvFormMHMaMatHang.ValidationGroup = validateGroup;
            refvFormMHTenMH.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblFormMHTenMatHang));
            refvFormMHTenMH.ValidationGroup = validateGroup;
            refvChungXe.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblChungXe));
            refvChungXe.ValidationGroup = validateGroup;
            refvXe.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblXe));
            refvXe.ValidationGroup = validateGroup;


            refvFormMHNhomMH.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblNhomMatHang));
            refvFormMHNhomMH.ValidationGroup = validateGroup;

            cusvHinh1.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblHinh1));
            cusvHinh1.ValidationGroup = validateGroup;

            cusvHinh2.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblHinh2));
            cusvHinh2.ValidationGroup = validateGroup;

            // refvMaPhuTung.ErrorMessage = string.Format(Resources.Resource.MESSAGE_REQUIRE_INPUT, CommonFunction.GetTextLabel(lblMaPhuTung));
            //refvMaPhuTung.ValidationGroup = validateGroup;

            //cusvGiaBanValid.ValidationGroup = validateGroup;
            // cusvGiaBanValid.ErrorMessage = string.Format(Resources.Resource.MESSAGE_VALIDATE_INPUT, CommonFunction.GetTextLabel(lblGiaBan));
            vsumMH.ValidationGroup = validateGroup;
            btnSave.ValidationGroup = validateGroup;
        }
        private void Update(MatHang objData, List<HinhAnhMatHang> lstImage)
        {
            int result = MatHangUtil.Update(objData, lstImage);
            if (result == 0)
                lblErrorMessage.Text = Resources.Resource.MESSAGE_UPDATE_ERROR;
            else if (result == -1)
                lblErrorMessage.Text = string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblMaPhuTung));
            else
                Response.Redirect(urlList);
        }

        private void Insert(MatHang objData, List<HinhAnhMatHang> lstImage)
        {
            int result = MatHangUtil.Insert(objData, lstImage);
            if (result == 0)
                lblErrorMessage.Text = Resources.Resource.MESSAGE_INSERT_ERROR;
            else if (result == -1)//MaPhuTung is exits
                lblErrorMessage.Text = string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblMaPhuTung));
            else if (result == -2)// Code is Exits
                lblErrorMessage.Text = string.Format(Resources.Resource.MESSAGE_EXISTS_ITEM, CommonFunction.GetTextLabel(lblFormMHMaMatHang));
            else
                Response.Redirect(urlList);
            //Delete image if insert error
            string img1 = string.Empty;
            string img2 = string.Empty;
            try
            {
                img1 = lstImage[0].ImageUrl;
            }
            catch
            { }
            try
            {
                img2 = lstImage[1].ImageUrl;
            }
            catch
            { }
            DeleteImageProduct(img1);
            DeleteImageProduct(img2);
        }
        #endregion

        #region Events, Handler

        protected void btnCacel_Click(object sender, EventArgs e)
        {
            Response.Redirect(urlList);
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Response.Redirect(this.GetCurrentPageAndParamaterUrl());
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                MatHang objData = new MatHang();
                List<HinhAnhMatHang> lstHinh = UploadHinh();
                if (drlPublish.SelectedValue == "1")
                    objData.IsPublished = true;
                else objData.IsPublished = false;
                objData.MaMatHang = txtFormMHMaMatHang.Text.Trim();
                objData.MaPhuTung = txtMaPhuTung.Text;
                objData.MaXe = ConvertValueObject.ParseInt(drlXe.SelectedValue);
                objData.TenMatHang = txtFormMHTenMH.Text.Trim();
                objData.MaNuocSanXuat = ConvertValueObject.ParseInt(drlFormMHNuocSX.SelectedValue);
                objData.MaLoaiHangHoa = ConvertValueObject.ParseInt(drlFormMHLoaiMH.SelectedValue);
                objData.Hieu = txtFormMHHieu.Text.Trim();
                objData.CreatedBy = objData.LastUpdatedBy = this.userLoginName;
                objData.CreatedDate = objData.LastUpdatedDate = CommonFunction.Now;
                objData.MaNhom = ConvertValueObject.ParseInt(drlFormMHNhomHH.SelectedValue);
                //objData.GiaBan = ConvertValueObject.ParseDouble(txtGiaBan.Text);
                // objData.CurencyCode = drlCurency.SelectedValue;
                objData.DVT = ConvertValueObject.ParseInt(drlDVT.SelectedValue);
                if (this.Command == CommonFunction.DEFAULT_COMMAND_ADD)
                    Insert(objData, lstHinh);
                else
                    Update(objData, lstHinh);

            }
            else
            {
                vsumMH.ShowMessageBox = false;
                vsumMH.ShowSummary = true;
            }
        }

        private List<HinhAnhMatHang> UploadHinh()
        {
            string imageOld1 = string.Empty;
            string imageOld2 = string.Empty;
            List<HinhAnhMatHangResult> lstOldPic = HinhAnhMatHangUtil.GetAllByMatHang(this.txtFormMHMaMatHang.Text);
            if (lstOldPic != null && lstOldPic.Count > 0)
            {
                imageOld1 = lstOldPic[0].ImageUrl;
                try
                {
                    imageOld2 = lstOldPic[1].ImageUrl;
                }
                catch
                {
                }
            }
            imageOld1 = UploadImage(ful1, imageOld1);
            imageOld2 = UploadImage(ful2, imageOld2);
            List<HinhAnhMatHang> lstResult = new List<HinhAnhMatHang>();
            lstResult.Add(new HinhAnhMatHang(txtFormMHMaMatHang.Text, imageOld1));
            lstResult.Add(new HinhAnhMatHang(txtFormMHMaMatHang.Text, imageOld2));
            return lstResult;
        }
        protected void drlChungXe_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDMXe();
        }
        #endregion

        #region Validate
        protected void CheckSGiaBanValid(object source, ServerValidateEventArgs args)
        {
            args.IsValid = CommonFunction.CheckSGiaIsValid(args.Value);
        }
        #endregion
        #region Images
        private void DeleteImageProduct(string fileName)
        {
            string fullPath = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT);
            // string pathSmall = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_SMALL);
            string pathlarge = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_LARGE);
            fullPath += "\\" + fileName;
            // pathSmall += "\\" + fileName;
            pathlarge += "\\" + fileName;
            CommonFunction.DeleteFile(fullPath);
            //  CommonFunction.DeleteFile(pathSmall);
            CommonFunction.DeleteFile(pathlarge);
        }
        private string UploadImage(FileUpload _ful, string _oldImage)
        {
            string result = string.Empty;
            if (_ful.HasFile)
            {
                string fileNameUpload = _ful.FileName;
                string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
                ImageFormat imgFormat = ImageUtility.GetFormatResizeImage(extFile);
                string fileName = txtFormMHMaMatHang.Text + "_" + DateTime.Now.ToString("yyyyMMdd") + "-" + Guid.NewGuid().ToString();
                result = fileName + extFile;
                string fullPath = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT);
                // string pathSmall = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_SMALL);
                string pathlarge = Server.MapPath(CommonFunction.DEFAULT_UPLOAD_PRODUCT_LARGE);
                if (!string.IsNullOrEmpty(_oldImage))
                {
                    this.DeleteImageProduct(_oldImage);
                }
                fullPath += "\\" + fileName + extFile;
                // pathSmall += "\\" + fileName + extFile;                
                pathlarge += "\\" + fileName + extFile;
                _ful.SaveAs(fullPath);
                // ImageUtility.ResizeImageFile(fullPath, pathSmall,300,imgFormat);                
                ImageUtility.ResizeImageFile(fullPath, pathlarge, CommonFunction.ImageProductWidth, imgFormat);
                //delete hinh goc
                CommonFunction.DeleteFile(fullPath);
                return result;
            }
            else return _oldImage;
        }
        private void DeleteImage(int index)
        {
            string imageOld1 = string.Empty;
            List<HinhAnhMatHangResult> lstOldPic = HinhAnhMatHangUtil.GetAllByMatHang(this.txtFormMHMaMatHang.Text);
            try
            {
                imageOld1 = lstOldPic[index].ImageUrl;
                DeleteImageProduct(imageOld1);
                Response.Redirect(Request.RawUrl);
            }
            catch
            {
            }

        }
        protected void lbtnDeleteHinh1_Click(object sender, EventArgs e)
        {
            DeleteImage(0);
        }
        protected void lbtnDeleteHinh2_Click(object sender, EventArgs e)
        {
            DeleteImage(1);
        }
        protected void CheckSHinh1Valid(object source, ServerValidateEventArgs args)
        {
            args.IsValid = CheckSImageValid(ful1);
        }
        protected void CheckSHinh2Valid(object source, ServerValidateEventArgs args)
        {
            args.IsValid = CheckSImageValid(ful2);
        }
        public bool CheckSImageValid(FileUpload ful)
        {
            bool result = false;
            if (ful.HasFile)
            {               
                string filePath = ful.FileName;
                if (filePath.Length > 0)
                {

                    string fileExtention = filePath.Substring(filePath.LastIndexOf(".") + 1);
                    fileExtention = "." + fileExtention + ";";
                    result = CommonFunction.ImageProductExtend.ToLower().IndexOf(fileExtention.ToLower()) >= 0;

                }               
            }
            return result;
        }
        #endregion
    }
}
